import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import styles from './SliderPuzzleVerification.module.css'
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';

const SliderPuzzleVerification = (props) => {
    const navigate = useNavigate();
    const [isVerified, setIsVerified] = useState(false);
    const [sliderValue, setSliderValue] = useState(0);
    const [gapPosition, setGapPosition] = useState(0);
    const [randomShape, setRandomShape] = useState('');
    const canvasRef = useRef(null);
    const puzzleImage = new Image();
    puzzleImage.src = 'https://pic1.zhimg.com/v2-a58fa2ab84be291418da2652805f8270_b.jpg';
    useEffect(() => {
        setIsVerified(false)      
    },[props.bool])
    useEffect(() => {
        const shapes = ['star', 'circle', 'triangle'];
        setRandomShape(shapes[Math.floor(Math.random() * shapes.length)]);
        const canvas = canvasRef.current;
        const ctx = canvas.getContext('2d');
        if (puzzleImage.complete) {
            drawPuzzle(ctx, canvas, gapPosition);
        } else {
            puzzleImage.onload = () => {
                drawPuzzle(ctx, canvas, gapPosition);
            };
        }
    }, [gapPosition]);

    const drawPuzzle = (ctx, canvas, gapX) => {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(puzzleImage, 0, 0, canvas.width, canvas.height);
        ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
        // 直接绘制三角形缺口
        drawTriangle(ctx, gapX + 15, canvas.height / 2, 30);

        // 绘制拖动的三角形形状
        if (!isVerified) {
            drawTriangleWithImage(ctx, gapX, sliderValue, canvas.height / 2, 30);
        }
    };
    useEffect(() => {
        props.handleClose(isVerified)
    }, [isVerified]);
    const drawStar = (ctx, cx, cy, spikes, outerRadius, innerRadius = outerRadius / 2) => {
        let rot = Math.PI / 2 * 3;
        let x = cx;
        let y = cy;
        let step = Math.PI / spikes;

        ctx.beginPath();
        ctx.moveTo(cx, cy - outerRadius);
        for (let i = 0; i < spikes; i++) {
            x = cx + Math.cos(rot) * outerRadius;
            y = cy + Math.sin(rot) * outerRadius;
            ctx.lineTo(x, y);
            rot += step;

            x = cx + Math.cos(rot) * innerRadius;
            y = cy + Math.sin(rot) * innerRadius;
            ctx.lineTo(x, y);
            rot += step;
        }
        ctx.lineTo(cx, cy - outerRadius);
        ctx.closePath();
        ctx.fill();
    };

    const drawStarWithImage = (ctx, gapX, sliderX, cy, spikes, outerRadius, innerRadius = outerRadius / 2) => {
        let rot = Math.PI / 2 * 3;
        let step = Math.PI / spikes;
        let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;

        // 计算星形的边界
        const points = [];
        for (let i = 0; i < spikes * 2; i++) {
            const radius = i % 2 === 0 ? outerRadius : innerRadius;
            const x = gapX + 15 + Math.cos(rot) * radius;
            const y = cy + Math.sin(rot) * radius;
            points.push([x, y]);
            minX = Math.min(minX, x);
            maxX = Math.max(maxX, x);
            minY = Math.min(minY, y);
            maxY = Math.max(maxY, y);
            rot += step;
        }

        // 创建一个临时画布来裁剪图片
        const tempCanvas = document.createElement('canvas');
        const tempCtx = tempCanvas.getContext('2d');
        tempCanvas.width = maxX - minX;
        tempCanvas.height = maxY - minY;

        // 绘制裁剪区域
        tempCtx.beginPath();
        for (let i = 0; i < points.length; i++) {
            const [x, y] = points[i];
            if (i === 0) {
                tempCtx.moveTo(x - minX, y - minY);
            } else {
                tempCtx.lineTo(x - minX, y - minY);
            }
        }
        tempCtx.closePath();
        tempCtx.clip();

        // 绘制裁剪后的图片，确保与缺口位置匹配
        tempCtx.drawImage(puzzleImage, minX - gapX - 15, 0, canvasRef.current.width, canvasRef.current.height, 0, 0, maxX - minX, maxY - minY);

        // 将裁剪后的图片绘制到拖动位置
        ctx.drawImage(tempCanvas, sliderX, cy - (maxY - minY) / 2);
    };

    const drawCircle = (ctx, cx, cy, radius) => {
        ctx.beginPath();
        ctx.arc(cx, cy, radius, 0, 2 * Math.PI);
        ctx.closePath();
        ctx.fill();
    };

    const drawCircleWithImage = (ctx, gapX, sliderX, cy, radius) => {
        const minX = gapX + 15 - radius;
        const maxX = gapX + 15 + radius;
        const minY = cy - radius;
        const maxY = cy + radius;

        const tempCanvas = document.createElement('canvas');
        const tempCtx = tempCanvas.getContext('2d');
        tempCanvas.width = maxX - minX;
        tempCanvas.height = maxY - minY;

        tempCtx.beginPath();
        tempCtx.arc(radius, radius, radius, 0, 2 * Math.PI);
        tempCtx.closePath();
        tempCtx.clip();

        tempCtx.drawImage(puzzleImage, minX - gapX - 15, 0, canvasRef.current.width, canvasRef.current.height, 0, 0, maxX - minX, maxY - minY);

        ctx.drawImage(tempCanvas, sliderX, cy - radius);
    };

    const drawTriangle = (ctx, cx, cy, sideLength) => {
        const height = (Math.sqrt(3) / 2) * sideLength;
        ctx.beginPath();
        ctx.moveTo(cx, cy - height / 2);
        ctx.lineTo(cx + sideLength / 2, cy + height / 2);
        ctx.lineTo(cx - sideLength / 2, cy + height / 2);
        ctx.closePath();
        ctx.fill();
    };

    const drawTriangleWithImage = (ctx, gapX, sliderX, cy, sideLength) => {
        const height = (Math.sqrt(3) / 2) * sideLength;
        const minX = gapX + 15 - sideLength / 2;
        const maxX = gapX + 15 + sideLength / 2;
        const minY = cy - height / 2;
        const maxY = cy + height / 2;

        const tempCanvas = document.createElement('canvas');
        const tempCtx = tempCanvas.getContext('2d');
        tempCanvas.width = maxX - minX;
        tempCanvas.height = maxY - minY;

        tempCtx.beginPath();
        tempCtx.moveTo(sideLength / 2, 0);
        tempCtx.lineTo(sideLength, height);
        tempCtx.lineTo(0, height);
        tempCtx.closePath();
        tempCtx.clip();

        tempCtx.drawImage(puzzleImage, minX - gapX - 15, 0, canvasRef.current.width, canvasRef.current.height, 0, 0, maxX - minX, maxY - minY);

        ctx.drawImage(tempCanvas, sliderX, cy - height / 2);
    };

    const handleSliderChange = (e) => {
        const value = parseInt(e.target.value, 10);
        setSliderValue(value);
        const canvas = canvasRef.current;
        const ctx = canvas.getContext('2d');
        drawPuzzle(ctx, canvas, gapPosition);
        if (Math.abs(value - gapPosition) < 5) {
            setIsVerified(true);
            // 使用 react-toastify 提示验证成功
            toast.success('验证成功！');
            setTimeout(() => {
                props.handleClose(isVerified,true) 
            },500)
        }
    };

    useEffect(() => {
        // 随机生成缺口位置
        setGapPosition(Math.floor(Math.random() * (250 - 30)) + 30);
    }, []);

    return (
        <div className={styles.sliderPuzzleVerification}>
            {isVerified ? (
                // 通过设置样式 display: none 隐藏提示信息
                <p style={{fontSize: '0.4rem',marginLeft: '40%',marginTop:"0.2rem" }}>验证通过！</p>
            ) : (
                <>
                    <canvas ref={canvasRef} style={{width: '60%',height: '100%'}}></canvas>
                    <div>

                        <p style={{ fontSize: '0.4rem',marginLeft: '2rem',lineHeight: '0.1rem' }}>拖动滑块完成拼图验证</p><br />
                        <input
                            type="range"
                            min="0"
                            max="270"
                            value={sliderValue}
                            onChange={handleSliderChange}
                            className={styles.slider}
                        />
                    </div>
                </>
            )}
            {/* 通过设置 display: none 隐藏 ToastContainer */}
            <ToastContainer style={{ display: 'none' }} />
        </div>
    );
};

export default SliderPuzzleVerification;